package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.changgou.canal.pojo.GoodsCode;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;

/**
 * Created by 柱子 on 2020/10/21 18:45 数据监控微服务
 */
@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @param entryType 对数据库操作的类型
     * @param rowData   对数据库操作的数据
     */

    @ListenPoint(schema = "changgou_goods", table = "tb_spu")
    public void goodsUp(CanalEntry.EntryType entryType, CanalEntry.RowData rowData) {

        //获取改变之前的数据转换为Map
        HashMap<String, String> oldMap = new HashMap<>();
        rowData.getBeforeColumnsList().forEach(c -> oldMap.put(c.getName(), c.getValue()));


        //获取改变之后的数据转换为Map
        HashMap<String, String> newMap = new HashMap<>();
        rowData.getAfterColumnsList().forEach(c -> newMap.put(c.getName(), c.getValue()));

        //获取最新上架的商品 is_marketable   0>1
        if (GoodsCode.GOODS_CODE_NO.getStatus().equals(oldMap.get("is_marketable"))
                && GoodsCode.GOODS_CODE_OK.getStatus().equals(newMap.get("is_marketable"))) {

            //将商品信息发送MQ
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE, "", newMap.get("id"));

        }


        //获取最新下架的商品信息 is_marketable1e 1->0

        if (GoodsCode.GOODS_CODE_OK.getStatus().equals(oldMap.get("is_marketable"))&&
                GoodsCode.GOODS_CODE_NO.getStatus().equals(newMap.get("is_marketable"))

        ){

            //商品信息发送到RabbitMQ

            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",newMap.get("id"));

        }



    }


}
